//
//  LYUIImageView+WeChat.swift
//  WeChat
//
//  Created by mac on 2018/7/30.
//  Copyright © 2018年 RRC. All rights reserved.
//

import Foundation
import UIKit
import Kingfisher

extension UIImageView{
    //原始图
    func ly_setImageWithURLString(_ URLString:String?, placeholderImage placeholder:UIImage? = nil){
        guard let URLString = URLString, let URL = URL(string: URLString) else {
            print("URL wrong")
            return
        }
        self.kf.setImage(with: URL)
    }
    
    //圆角图
    func ly_setCircularImageWithURLString(_ URLString:String?, placeholderImage placeholder:UIImage? = nil){
        self.ly_setRoundImageWithURLString(URLString, placeholderImage: placeholder, cornerRadiusRatio: self.ts_width/2, progressBlcok: nil)
    }
    
    //设置 cornerRadiusRatio
    func ly_setCornerRadiusImageWithURLString(_ URLString:String?, placeholderImage placeholder:UIImage? = nil, cornerRadiusRatio:CGFloat? = nil){
        self.ly_setRoundImageWithURLString(URLString, placeholderImage: placeholder, cornerRadiusRatio: cornerRadiusRatio, progressBlcok: nil)
    }
    
    
    func ly_setRoundImageWithURLString(_ URLString:String?, placeholderImage placeholder:UIImage? = nil, cornerRadiusRatio:CGFloat? = nil, progressBlcok:ImageDownloaderProgressBlock? = nil){
        guard let URLString = URLString, let URL = URL(string: URLString) else {
            print("URL wrong")
            return
        }
        let memoryImage = KingfisherManager.shared.cache.retrieveImageInMemoryCache(forKey: URLString)
        let diskImage = KingfisherManager.shared.cache.retrieveImageInDiskCache(forKey: URLString)
        guard let image = memoryImage ?? diskImage else {
            let optionInfo:KingfisherOptionsInfo = [
                .forceRefresh,
            ]
            KingfisherManager.shared.downloader.downloadImage(with: URL, retrieveImageTask: RetrieveImageTask.empty, options: optionInfo, progressBlock: progressBlcok) { (image, error, imageURL, originalData) in
                if let image = image, let originalData = originalData{
                    DispatchQueue.global(qos: .default).async {
                        let roundedImage = image.ts_roundWithCornerRadius(image.size.width * (cornerRadiusRatio ?? 0.5))
                        KingfisherManager.shared.cache.store(roundedImage, original: originalData, forKey: URLString, processorIdentifier: "", cacheSerializer: DefaultCacheSerializer.default, toDisk: true, completionHandler: {
                            self.ly_setImageWithURLString(URLString)
                        })
                    }
                }
            }
            return
        }
        self.image = image
    }
}
